package com.lian.community.controller.user;

import com.lian.community.async.EventModel;
import com.lian.community.async.EventProducer;
import com.lian.community.constant.EntityType;
import com.lian.community.constant.EventType;
import com.lian.community.constant.RedisKeyType;
import com.lian.community.constant.ResponseCode;
import com.lian.community.entity.user.HostUser;
import com.lian.community.entity.user.User;
import com.lian.community.service.token.TokenService;
import com.lian.community.service.user.UserService;
import com.lian.community.util.RedisKeyUtil;
import com.lian.community.util.ResponseUtil;
import com.lian.community.util.SaltUtil;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 要设置一下不允许重名
 * 加了个rememberMe功能
 * 设置了cookie过期时间为14天，session为服务器重启则无
 * 把token存到redis中，设置expire time（14天）
 */
@Controller
@PropertySource(value={"classpath:user.properties"}, encoding="utf-8")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    EventProducer eventProducer;
    @Autowired
    HostUser hostUser;

    @Value("${nameLength}")
    int nameLength;
    @Value("${passwordMin}")
    int passwordMin;
    @Value("${passwordMax}")
    int passwordMax;
    public static final int COOKIE_EXPIRE_TIME = 100800;


    @RequestMapping(value = "/loginAndPersistence")
    public void loginAndPersistence(@RequestParam("name")String name, @RequestParam("password")String password,
                          @RequestParam(required = false)String next,
                          HttpServletResponse response, HttpSession session){
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        Map<String,Integer> resMesg = new HashMap<>(1);
        if(!user.registerValid(nameLength, passwordMin, passwordMax)){
            ResponseUtil.responseCode(response,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        Map<String,Object> map = userService.login(user);
            if(map.get("id") == null){
                ResponseUtil.responseCode(response,ResponseCode.PARAM_ILLEGAL);
                return;
            }
        int id =(Integer)map.get("id");
        String useMesg = RedisKeyUtil.get(id, EntityType.USER, RedisKeyType.LOGIN_PERSISTENCE);
        String token = useMesg + SaltUtil.getSalt();
        tokenService.addToken(useMesg,token);
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(COOKIE_EXPIRE_TIME);
        response.addCookie(cookie);
        session.setAttribute("token",token);
        resMesg.put("succeed",ResponseCode.REQUEST_SUCCEED);
        ResponseUtil.responseCode(response,ResponseCode.REQUEST_SUCCEED);
    }

    /**
     * 这个地方有问题
     * @param name
     * @param password
     * @param next
     * @param response
     * @return
     */
    @RequestMapping(value = "/doLogin")
    public void doLogin(@RequestParam("name")String name, @RequestParam("password")String password,
                        @RequestParam(required = false)String next,
                        HttpServletResponse response, HttpSession session){
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        Map<String,Integer> resMesg = new HashMap<>(1);
        if(!user.registerValid(nameLength, passwordMin, passwordMax)){
            ResponseUtil.responseCode(response,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        Map<String,Object> map = userService.login(user);
        if(map.get("id") == null){
            ResponseUtil.responseCode(response,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        int id =(Integer)map.get("id");
        String useMesg = RedisKeyUtil.get(id, EntityType.USER, RedisKeyType.LOGIN_PERSISTENCE);
        String token = useMesg + SaltUtil.getSalt();
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(COOKIE_EXPIRE_TIME);
        session.setAttribute("token",token);
        response.addCookie(cookie);
        ResponseUtil.responseCode(response,ResponseCode.REQUEST_SUCCEED);
    }
    /**
     * test
     * @return
     */
    @RequestMapping(value = "/index")
    public String test(){
        System.out.println(Thread.currentThread().getName());
        return "index";

    }

    /**
     * test
     * @return
     */
    @RequestMapping(value = "/hello")
    public String hello(){
        System.out.println(Thread.currentThread().getName());
        return "hello";

    }

    @RequestMapping(value = "/reg")
    public void register(@RequestParam("name")String name, @RequestParam("password")String password,
                           HttpServletResponse response){
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        if(!user.registerValid(nameLength, passwordMin, passwordMax)){
            ResponseUtil.responseCode(response,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        Integer id;
        try {
            id = userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.responseCode(response,ResponseCode.SERVER_ERROR);
            return;
        }
        eventProducer.add(new EventModel(EventType.REGISTER).setEntityType(EntityType.USER));
        ResponseUtil.responseCode(response,ResponseCode.REQUEST_SUCCEED);
    }
}

